package jdktcp.server;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JDKTcpServer {
    static int port = 9999;
    static String host = null;

    static ExecutorService pool = Executors.newFixedThreadPool(10);

    public JDKTcpServer() throws Exception {
        ServerSocket server = new ServerSocket();
        if (host != null) {
            server.bind(new InetSocketAddress(host, port));
        } else {
            server.bind(new InetSocketAddress(port));
        }

        System.out.println("init server :" + server);
        while (true) {
            Socket socket = server.accept();
            System.out.println("--->" + socket);
            execute(socket);
        }
    }

    private void execute(Socket socket) {
        pool.execute(() -> {
            try {
                InputStream in = socket.getInputStream();
                int firstByte = in.read();
                System.out.println("revice first char:" + new String(new byte[]{(byte) firstByte}));
                switch (firstByte) {
                    case 49:
                        read1(in);
                        break;
                    case 50:
                        read2(in);
                        break;
                    default:
                        break;
                }

                OutputStream out = socket.getOutputStream();
                out.write("nihao".getBytes());
                System.out.println("send resp finish <---");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(socket);
            }
        });
    }

    private String read1(InputStream in) throws IOException {
        byte[] buff = new byte[1024];
        in.read(buff);
        String req = new String(buff).trim();
        System.out.println("revice==>" + req);
        return req;
    }

    private String read2(InputStream in) throws IOException {
        byte[] buff = IOUtils.toByteArray(in);
        String req = new String(buff);
        System.out.println("revice==>" + req);
        return req;
    }

    public static void main(String[] args) throws Exception {
        new JDKTcpServer();
    }
}
